import {defineStore} from "pinia";
import {useMemberStore} from "@/common/member.ts";
import {defaults, mande} from 'mande'
//全局配置
defaults.headers.Authorization = 'MS4xNzUwOTI4Mjg1LjE3NTEwMTQ2ODU=.d55af7cc5330f008d0eecd25873ab47f'

interface State {
    id: number,
    name: string;
    email: string,
    score: number,
    sub: State[],
    list: Question[],
    loading:boolean,
}

interface Question {
    id: number,
    title: string,
    type: number,
    options: Array<string>,
    answer: Array<number>,
    score: number,

}

interface Result {
    code: number,
    info: string,
    data: any,
}

const prefix = import.meta.env.VITE_API_URL;
export const useUserStore = defineStore("userStore", {
    state: (): State => {
        return {
            id: 1799,
            name: '张三',
            score: 0,
            email: '694995669@qq.com',
            sub: [] as State[],
            list: [] as Question[],
            loading: true,

        }
    },
    getters: {
        doubleScore(state: State) {
            return state.score * 2;
        },
        doubleAddOne(): number {
            return this.doubleScore + 1;
        },
        times(state: State): Function {
            return (x: number) => this.score * x;
        },
        avatar(state: State): string {
            const member = useMemberStore();
            return member.headerImg;
        }
    },
    actions: {
        add(num: number) {
            this.score += num;
            return this.score;
        },
        rand() {
            this.score = Math.floor(Math.random() * 100);
        },

        option(idx: number) {
            return String.fromCharCode(65 + idx)
        },
         async question() {
             try {
                 const api = mande(`${prefix}/api/exam/questions`);
                 this.list = await api.get().then((res) => {
                     console.log('res===>', res);
                     let ret = res as Result;
                     if (ret.code == 1) {
                         this.loading = false;
                         return ret.data;
                     } else {//error

                     }
                 });
             } catch (error) {
                 console.log(error);
                 return error;
             }
         },
    }
});